<template>
  <div class="car-detail-page">
    <div class="container">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/cars' }">车辆列表</el-breadcrumb-item>
        <el-breadcrumb-item>车辆详情</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="detail-content" v-if="currentCar">
        <div class="detail-main">
          <!-- 图片展示 -->
          <div class="image-section">
            <div class="main-image">
              <img 
                :src="currentImage" 
                :alt="currentCar.title"
                @error="handleImageError"
              >
            </div>
            <div class="image-thumbs">
              <div
                v-for="(img, index) in currentCar.images"
                :key="index"
                class="thumb"
                :class="{ active: currentImageIndex === index }"
                @click="currentImageIndex = index"
              >
                <img 
                  :src="img" 
                  :alt="`图片${index + 1}`"
                  @error="handleThumbError"
                >
              </div>
            </div>
          </div>

          <!-- 基本信息 -->
          <div class="info-section">
            <el-card class="info-card">
              <h1 class="car-title">{{ currentCar.title }}</h1>
              <p class="car-subtitle">{{ currentCar.subtitle }}</p>
              
              <div class="price-section">
                <div class="current-price">
                  <span class="price">{{ currentCar.price }}万</span>
                  <span class="original-price" v-if="currentCar.original_price">
                    新车{{ currentCar.original_price }}万
                  </span>
                </div>
                <div class="price-desc">包过户费，可选分期付款</div>
              </div>

              <div class="basic-info">
                <div class="info-grid">
                  <div class="info-item">
                    <label>上牌时间</label>
                    <span>{{ formatRegDate(currentCar.reg_date) }}</span>
                  </div>
                  <div class="info-item">
                    <label>行驶里程</label>
                    <span>{{ currentCar.distance }}万公里</span>
                  </div>
                  <div class="info-item">
                    <label>排放标准</label>
                    <span>{{ currentCar.emission }}</span>
                  </div>
                  <div class="info-item">
                    <label>变速箱</label>
                    <span>{{ currentCar.gearbox === 'auto' ? '自动' : '手动' }}</span>
                  </div>
                  <div class="info-item">
                    <label>排量</label>
                    <span>{{ currentCar.displacement }}L</span>
                  </div>
                  <div class="info-item">
                    <label>所在地</label>
                    <span>{{ currentCar.location }}</span>
                  </div>
                </div>
              </div>

              <div class="car-tags" style="margin-bottom: 20px;">
                <el-tag v-if="currentCar.is_new" type="success" size="small">准新车</el-tag>
                <el-tag v-if="currentCar.hot" type="danger" size="small">热门</el-tag>
              </div>

              <div class="action-buttons">
                <el-button type="primary" size="large" @click="handleContact">
                  <el-icon><Phone /></el-icon>
                  联系卖家
                </el-button>
                <el-button 
                  :type="isFavorite ? 'danger' : 'default'" 
                  size="large"
                  @click="handleFavorite"
                >
                  <el-icon><Star /></el-icon>
                  {{ isFavorite ? '已收藏' : '收藏' }}
                </el-button>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 详细信息 -->
        <div class="detail-sections">
          <!-- 车辆配置 -->
          <el-card class="detail-card" v-if="currentCar.configurations && currentCar.configurations.length > 0">
            <template #header>
              <h3>车辆配置</h3>
            </template>
            <div class="config-grid">
              <div
                v-for="config in currentCar.configurations"
                :key="config.name"
                class="config-item"
              >
                <el-icon v-if="config.available" class="icon-available"><Check /></el-icon>
                <el-icon v-else class="icon-unavailable"><Close /></el-icon>
                <span>{{ config.name }}</span>
              </div>
            </div>
          </el-card>

          <!-- 检测报告 -->
          <el-card class="detail-card" v-if="currentCar.inspections && currentCar.inspections.length > 0">
            <template #header>
              <h3>专业检测报告</h3>
            </template>
            <div class="inspection-list">
              <div
                v-for="item in currentCar.inspections"
                :key="item.name"
                class="inspection-item"
                :class="{ passed: item.passed }"
              >
                <el-icon v-if="item.passed" color="#67C23A"><Check /></el-icon>
                <el-icon v-else color="#F56C6C"><Close /></el-icon>
                <span>{{ item.name }}</span>
                <span class="result">{{ item.result || item.result_description }}</span>
              </div>
            </div>
          </el-card>

          <!-- 车主信息 -->
          <el-card class="detail-card" v-if="currentCar.seller">
            <template #header>
              <h3>车主信息</h3>
            </template>
            <div class="seller-info">
              <div class="seller-avatar">
                <el-avatar 
                  :size="60" 
                  :src="currentCar.seller.avatar || '/images/default-avatar.png'"
                >
                  <el-icon><UserFilled /></el-icon>
                </el-avatar>
              </div>
              <div class="seller-details">
                <h4>{{ currentCar.seller.name }}</h4>
                <p>认证车主 · {{ currentCar.seller.carCount || 1 }}辆车</p>
                <div class="seller-tags">
                  <el-tag size="small" type="success">实名认证</el-tag>
                  <el-tag size="small">车况真实</el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <div v-else-if="carStore.loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>

      <div v-else class="error-container">
        <el-empty description="车辆信息加载失败" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { Phone, Star, Check, Close, UserFilled } from '@element-plus/icons-vue'
import { useCarStore } from '@/store/car'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'

// 初始化核心变量
const route = useRoute()
const carStore = useCarStore()
const userStore = useUserStore()
const currentImageIndex = ref(0)

// 当前车辆数据
const currentCar = computed(() => {
  return carStore.carDetail
})

// 格式化上牌日期
const formatRegDate = (regDate) => {
  if (!regDate) return ''
  // 如果是 Date 对象
  if (regDate instanceof Date) {
    return regDate.toISOString().split('T')[0].replace(/-/g, '-')
  }
  // 如果是字符串
  if (typeof regDate === 'string') {
    return regDate.split('T')[0]
  }
  return regDate
}

// 1. 计算当前显示的主图
const currentImage = computed(() => {
  if (!currentCar.value || !currentCar.value.images || currentCar.value.images.length === 0) {
    return '/images/default-car.png'
  }
  return currentCar.value.images[currentImageIndex.value]
})

// 2. 收藏状态判断
const isFavorite = computed(() => {
  if (!currentCar.value || !carStore.favorites.length) return false
  return carStore.favorites.some(fav => fav.id === currentCar.value.id)
})

// 3. 图片加载失败兜底方法
const handleImageError = (e) => {
  e.target.src = '/images/default-car.png'
  e.target.alt = '车辆图片加载失败'
}

const handleThumbError = (e) => {
  e.target.src = '/images/default-car.png'
  e.target.alt = '缩略图加载失败'
}

// 4. 联系卖家方法
const handleContact = () => {
  const sellerPhone = currentCar.value?.seller?.phone || '400-123-4567'
  ElMessage.success(`联系卖家: ${sellerPhone}`)
}

// 5. 收藏/取消收藏方法
const handleFavorite = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }
  try {
    const carId = currentCar.value.id
    if (isFavorite.value) {
      await carStore.removeFavorite(carId)
      ElMessage.success('取消收藏成功')
    } else {
      await carStore.addFavorite(carId)
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  }
}

// 6. 获取车辆详情
const fetchCarDetail = async (carId) => {
  try {
    await carStore.fetchCarDetail(carId)
  } catch (error) {
    console.error('获取车辆详情失败:', error)
    ElMessage.error('获取车辆信息失败')
  }
}

// 7. 生命周期：加载车辆详情
onMounted(async () => {
  const carId = route.params.id
  if (carId) {
    await fetchCarDetail(carId)
  }
})

// 8. 监听路由参数变化
watch(() => route.params.id, async (newId) => {
  if (newId) {
    await fetchCarDetail(newId)
    currentImageIndex.value = 0
  }
})
// 卖家头像URL计算
const sellerAvatarUrl = computed(() => {
  if (!currentCar.value?.seller?.avatar) {
    return '/images/default-avatar.png'
  }
  
  const avatarPath = currentCar.value.seller.avatar
  // 使用API服务路径
  const timestamp = Date.now()
  return `/api/avatar/${avatarPath}?t=${timestamp}`
})
</script>

<style lang="scss" scoped>
.car-detail-page {
  padding: 20px 0;

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
}

.breadcrumb {
  margin-bottom: 20px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-main {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 30px;
}

.image-section {
  .main-image {
    height: 400px;
    margin-bottom: 10px;
    border-radius: 8px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .image-thumbs {
    display: flex;
    gap: 10px;
    overflow-x: auto;

    .thumb {
      width: 80px;
      height: 60px;
      border: 2px solid transparent;
      border-radius: 4px;
      cursor: pointer;
      flex-shrink: 0;
      overflow: hidden;

      &.active {
        border-color: #ff6a00;
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}

.info-section {
  .info-card {
    position: sticky;
    top: 20px;

    .car-title {
      margin: 0 0 8px;
      font-size: 24px;
      color: #333;
      line-height: 1.4;
    }

    .car-subtitle {
      margin: 0 0 20px;
      color: #666;
      font-size: 14px;
    }

    .price-section {
      margin-bottom: 24px;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 6px;

      .current-price {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 8px;

        .price {
          font-size: 28px;
          font-weight: bold;
          color: #ff6a00;
        }

        .original-price {
          font-size: 14px;
          color: #999;
          text-decoration: line-through;
        }
      }

      .price-desc {
        font-size: 12px;
        color: #666;
      }
    }

    .basic-info {
      margin-bottom: 24px;

      .info-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;

        .info-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 8px 0;
          border-bottom: 1px solid #f0f0f0;

          label {
            color: #666;
            font-size: 14px;
          }

          span {
            font-weight: 500;
            color: #333;
          }
        }
      }
    }

    .action-buttons {
      display: flex;
      gap: 12px;

      .el-button {
        flex: 1;
      }
    }
  }
}

.detail-sections {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-card {
  :deep(.el-card__header) {
    border-bottom: 1px solid #f0f0f0;
    padding: 16px 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      color: #333;
    }
  }
}

.config-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;

  .config-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;

    .icon-available {
      color: #67C23A;
    }

    .icon-unavailable {
      color: #F56C6C;
    }

    span {
      font-size: 14px;
      color: #333;
    }
  }
}

.inspection-list {
  .inspection-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    &.passed {
      .result {
        color: #67C23A;
      }
    }

    &:not(.passed) {
      .result {
        color: #F56C6C;
      }
    }

    span {
      flex: 1;
      font-size: 14px;
    }

    .result {
      font-size: 12px;
      color: #666;
    }
  }
}

.seller-info {
  display: flex;
  gap: 16px;
  align-items: center;

  .seller-details {
    flex: 1;

    h4 {
      margin: 0 0 4px;
      font-size: 16px;
      color: #333;
    }

    p {
      margin: 0 0 8px;
      color: #666;
      font-size: 14px;
    }

    .seller-tags {
      display: flex;
      gap: 8px;
    }
  }
}

.loading-container,
.error-container {
  padding: 60px 0;
}

@media (max-width: 768px) {
  .detail-main {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .image-section {
    .main-image {
      height: 300px;
    }
  }

  .info-section {
    .info-card {
      position: static;
    }
  }

  .config-grid {
    grid-template-columns: 1fr;
  }
}
</style>